//日志
const {
    logger
} = require('../config/logger');

//引入数据库连接池
const pool = require('../config/mysql');
//引入数据库语句
const queryLease = require('../db/leaseQuery/leaseQuery');
const queryUser = require('../db/userQuery/userQuery');

//解析token
const {
    token_verify
} = require('../config/jwt')

//引入时间模块
const sd = require('silly-datetime');

function leaseChat(io, hashName, socket) {
    socket.on('talkTo_lease', function (data) {
        const toReceiverId = data.to; //接收者ID
        const token = data.token;
        const {
            userId
        } = token_verify(token); //发送者ID
        const message = data.message; //发送消息
        const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm'); //发送日期
        pool.query(queryLease.insert_chat, [userId, toReceiverId, message, time], (error, result) => {
            if (error) {
                logger().error("存储聊天记录失败: " + error);
                return;
            } else {
                if (hashName.has(toReceiverId)) {
                    pool.query(queryUser.getUser_info_id, userId, (error, result) => {
                        if (error) {
                            const toSocket = hashName.get(toReceiverId); //获取接收者socketID
                            io.to(toSocket).emit('message', JSON.stringify(
                                "发送消息失败:"
                            ));
                            logger().error("发送消息失败: " + error);
                            return;
                        } else {
                            const {
                                nickName,
                                avatarUrl
                            } = JSON.parse(JSON.stringify(result[0]));
                            const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
                            const toSocket = hashName.get(toReceiverId); //获取接收者socketID
                            io.to(toSocket).emit('message', JSON.stringify({
                                nickName,
                                avatarUrl,
                                message,
                                time
                            }));
                        }
                    });
                }
            }
        });
    });
}

module.exports = leaseChat;